package cn.tedu.sgos.utils;

import cn.hutool.captcha.generator.RandomGenerator;
import cn.tedu.sgos.base.model.SMSModel;
import com.cloopen.rest.sdk.BodyType;
import com.cloopen.rest.sdk.CCPRestSmsSDK;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.HashMap;

/**
 * @Author: Miyako
 * @Date: 2024-09-06-11:06
 * @Description:短信工具包
 */
@Component
public class SMSUtil {

    @Autowired
    SMSModel smsModel;


    //生成验证码并发送短信
    public String generateSMS(String phone) {

        //生产环境请求地址：app.cloopen.com
        String serverIp = "app.cloopen.com";
        //请求端口
        String serverPort = "8883";
        //主账号,登陆云通讯网站后,可在控制台首页看到开发者主账号ACCOUNT SID和主账号令牌AUTH TOKEN
        String accountSId = smsModel.getAccountId();
        String accountToken = smsModel.getAuthToken();
        //请使用管理控制台中已创建应用的APPID
        String appId = smsModel.getAppId();
        CCPRestSmsSDK sdk = new CCPRestSmsSDK();
        sdk.init(serverIp, serverPort);
        sdk.setAccount(accountSId, accountToken);
        sdk.setAppId(appId);
        sdk.setBodyType(BodyType.Type_JSON);
        String to = phone;
        String templateId= "1";//测试变量为1不用改
        //生成随机四位数字验证码                                             随机池       总长度
        RandomGenerator randomGenerator = new RandomGenerator("0123456789",4);
        String randomNum = randomGenerator.generate();
        Long expire = 1L; //有效期 1min
        String[] datas = {randomNum,expire.toString()};
        //发送
        HashMap<String, Object> result = sdk.sendTemplateSMS(to,templateId,datas);
        //接收状态码全0发送成功
        if("000000".equals(result.get("statusCode"))){
            return randomNum;
        }else{
            //发送错误,返回具体错误码(可修改)
           throw new  RuntimeException("验证码生成错误"+result.get("statusCode").toString());
        }

    }




}
